package com.zhangtai.modules.controller.admin;

import cn.hutool.db.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.*;
import com.zhangtai.modules.dto.GroupEntityDto;
import com.zhangtai.modules.dto.RoleAndRoleMenuInfoDto;
import com.zhangtai.modules.dto.UserAndUserRoleInfoDto;
import com.zhangtai.modules.entity.system.*;
import com.zhangtai.modules.service.system.*;
import com.zhangtai.modules.vo.*;
import com.zhangtai.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

@RestController
@Api(tags="权限分配接口")
@RequestMapping("roleAssignment")
@Slf4j
public class UserRoleController {

	@Autowired
    private LoginController loginController;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private RoleMenuService roleMenuService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private OrgGroupService orgGroupService;
	@Autowired
	private RoleMenuDao roleMenuDao;
	@Autowired
	private UserRoleDao userRoleDao;
	@Autowired
	private MenuDao menuDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private UserGroupService userGroupService;
	@Autowired
	private UserGroupDao userGroupDao;
	@Autowired
	private OrgGroupDao orgGroupDao;
	@Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
	@Autowired
	private UserService userService;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private UserDao userDao;
	
	@PostMapping("/queryUserList")
	@ApiOperation(value = "分页查询用户接口")
	@PreAuthorize("hasAuthority('sys:admin:get')")
	public R<PageResult<UserEntity>> queryUserList( @RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){
	
		return R.ok(userService.queryPage(name, pageNum, pageSize));
	}

	@PostMapping("/queryRoleList")
	@ApiOperation(value = "分页查询角色接口")
	@PreAuthorize("hasAuthority('sys:admin:get')")
	public R<PageResult<RoleEntity>> queryRoleList(@RequestParam(value = "name", required = false) String name,
												   @RequestParam(value = "roleName", required = false) String roleName,
												   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
												   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){

		return R.ok(roleService.queryPage(name, roleName,pageNum, pageSize));
	}
	@PostMapping("/queryMenuList")
	@ApiOperation(value = "分页查询菜单接口")
	@PreAuthorize("hasAuthority('sys:admin:get')")
	public R<PageResult<MenuEntity>> queryMenuList(@RequestParam(value = "keyword", required = false) String keyword,
												   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
												   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){

		return R.ok(menuService.queryPage(keyword ,pageNum, pageSize));
	}

	@PostMapping("/queryOrgGroupList")
	@ApiOperation(value = "分页查询公司组接口")
	@PreAuthorize("hasAuthority('sys:admin:get')")
	public R<PageResult<OrgGroupEntity>> queryOrgGroupList(@RequestParam(value = "keyword", required = false) String keyword,
														   @RequestParam(value = "groupName", required = false) String groupName,
												   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
												   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){

		return R.ok(orgGroupService.queryPage(keyword,groupName,pageNum,pageSize));
	}
	@GetMapping("/getRoleMenuInterface")
    @ApiOperation(value = "根据角色ID获取角色接口")
	@PreAuthorize("hasAuthority('sys:admin:get')")
	public R getRoleMenu(@RequestParam(value = "roleId", required = false) Long roleId,String type) {
		//List<RoleMenuEntity> list = roleMenuDao.selectList(new QueryWrapper<RoleMenuEntity>().eq("role_id", roleId).eq("is_delete", 0));
		List<JSONObject>  list=roleMenuDao.getRoleMenuById(roleId,type);
		List<RoleAndRoleMenuInfoDto>  roleAndRoleMenuInfoDtos=new ArrayList<>();
		for (JSONObject object:list){
			RoleAndRoleMenuInfoDto rmo=new RoleAndRoleMenuInfoDto();
			rmo.setRoleId(object.getLong("role_id"));
			rmo.setMenuId(object.getLong("menu_id"));
			rmo.setDelete(object.getBoolean("is_delete"));
			rmo.setName(object.getString("name"));
			rmo.setRoleName(object.getString("role_name"));
			roleAndRoleMenuInfoDtos.add(rmo);
		}
		return R.ok(roleAndRoleMenuInfoDtos);
	}
	
	@GetMapping("/queryRoleEntityListInterface")
	@ApiOperation(value = "查询角色列表接口")
	@PreAuthorize("hasAuthority('sys:admin:get')")
	public R getRoleList(){
		List<RoleEntity> list=roleDao.selectList(new QueryWrapper<RoleEntity>().eq("is_delete", 0));
		return R.ok(list) ;
	}
	
	@GetMapping("/queryMenuEntityListInterface")
	@ApiOperation(value = "查询菜单列表接口")
	@PreAuthorize("hasAuthority('sys:admin:get')")
	public R menuList(@RequestParam(value = "type" , required = false) String type){

		Integer i =null;
		if (!StringUtils.isEmpty(type)){
			i=TypeCastUtils.toInt(type);
		}


		List<MenuEntity> list= menuDao.selectList(new QueryWrapper<MenuEntity>().eq("is_delete", 0).
				eq(!StringUtils.isEmpty(type),"type",i));

		return R.ok(list) ;
	}
	
	@GetMapping("/getUserGroupListInterface")
    @ApiOperation(value = "根据组ID查询用户组列表接口")
	@PreAuthorize("hasAuthority('sys:admin:get')")
	public R getUserGroupListInterface(@RequestParam(value = "userId", required = false) Integer userId){
		List<UserGroupEntity> list=userGroupDao.selectList(new QueryWrapper<UserGroupEntity>().eq("user_id", userId).eq("is_delete", 0));
		return R.ok(list) ;
	}
	
	@GetMapping("/queryOrgGroupListInterface")
    @ApiOperation(value = "查询公司组列表接口")
	@PreAuthorize("hasAuthority('group:admin:get')")
	public R getOrgGroupList(){
		List<GroupEntityDto> list= orgGroupDao.getOrgGroupList();
		return R.ok(list) ;
	}
	
	@PostMapping("/getUserRoleInterface")
    @ApiOperation(value = "根据用户ID获取角色接口")
	@PreAuthorize("hasAuthority('sys:admin:get')")
	public R getUserRole(@RequestParam(value = "userId", required = false) Long userId) {
		List<JSONObject>  list=userRoleDao.getUserRoleById(userId);
		List<UserAndUserRoleInfoDto>  listUser=new ArrayList<>();
		for (JSONObject jsonObject:list){
			UserAndUserRoleInfoDto userAndUserRoleInfoDto=new UserAndUserRoleInfoDto();
			userAndUserRoleInfoDto.setName(jsonObject.getString("name"));
			userAndUserRoleInfoDto.setRoleId(jsonObject.getLong("role_id"));
			userAndUserRoleInfoDto.setRoleName(jsonObject.getString("role_name"));
			userAndUserRoleInfoDto.setUserId(jsonObject.getLong("user_id"));
			userAndUserRoleInfoDto.setDelete(jsonObject.getBoolean("is_delete"));
			listUser.add(userAndUserRoleInfoDto);
		}
		return R.ok(listUser);
	}

	@PostMapping("/saveRoleInterface")
	@ApiOperation(value = "角色保存接口")
	@SysAuthorityLog(value = "角色保存接口")
	@PreAuthorize("hasAuthority('sys:admin:update')")
	public R saveRole(@RequestBody RoleVo roleVo) {
		RoleEntity roleEntity= BeanUtilsMabach.doToDto(roleVo,RoleEntity.class);
		R r;
		if(roleEntity.getRoleId()==null){
			roleEntity.setCreateTime(new Date());
			roleEntity.setIsDelete(0);
			//保存新增
			r=roleService.saveE(roleEntity);
		}else {
			//修改
			r=roleService.updateByIdE(roleEntity);
		}
		return r;
	}
	
	@PostMapping("/saveMenuInterface")
	@ApiOperation(value = "菜单保存接口")
	@SysAuthorityLog(value = "菜单保存接口")
	@PreAuthorize("hasAuthority('sys:admin:update')")
	public R saveMenu(@RequestBody MenuEntity menuEntity) {
		menuEntity.setIsDelete(0);
		menuEntity.setCreateTime(new Date());

		return menuService.saveE(menuEntity);
	}
	
	@PostMapping("/saveOrgGroupInterface")
    @ApiOperation(value="保存公司组接口")
	@SysAuthorityLog(value = "保存公司组接口")
    @Transactional
	@PreAuthorize("hasAuthority('group:admin:update')")
	public R saveOrgGroup(@RequestBody @Valid List<OrgGroupEntity> OrgGroupEntitys) {
		
		if(!CollectionUtils.isEmpty(OrgGroupEntitys)) {
			//自动生成流水ID
			long flowId = snowflakeIdWorker.nextId();
			
			Timestamp d = new Timestamp(System.currentTimeMillis());
			
			for(OrgGroupEntity item:OrgGroupEntitys) {
				OrgGroupEntity orgGroupEntity = new OrgGroupEntity();
				orgGroupEntity.setGroupId(flowId);
				orgGroupEntity.setOrgId(item.getOrgId());
				orgGroupEntity.setGroupName(item.getGroupName());
				orgGroupEntity.setOrgName(item.getOrgName());
				orgGroupEntity.setIsDelete(0);
				orgGroupEntity.setCreateTime(d);
				
				//新增保存
				orgGroupService.saveE(orgGroupEntity);
			}
		}
		return R.ok();
	}

	@PostMapping("/updateRoleByIdEInterface")
    @ApiOperation(value="更新/新增用户角色-中间表接口")
	@SysAuthorityLog(value = "更新/新增用户角色-中间表接口")
	@PreAuthorize("hasAuthority('sys:admin:update')")
    @Transactional
	public R updateByIdE(@RequestBody @Valid UserRoleVo userRoleVo,HttpServletRequest request) throws Exception {
		 
		 if(!ObjectUtils.isEmpty(userRoleVo)) {
			 userRoleDao.deleteUserRole(userRoleVo.getUserId());
			 if(!CollectionUtils.isEmpty(userRoleVo.getRoleIds())) {
				 for(Long item:userRoleVo.getRoleIds()) {
					 UserRoleEntity userRole = new UserRoleEntity();
					 userRole.setUserId(userRoleVo.getUserId());
					 userRole.setRoleId(item);
					 userRole.setIsDelete(0);
					 //保存
					 userRoleService.saveE(userRole);
				 }
			 }

			 //			删除缓存中的登录状态，使权限重新生效
			 Long userId = userRoleVo.getUserId();
			 UserEntity userEntity = userService.getByIdE(userId);
			 if (!ObjectUtils.isEmpty(userEntity)){
				 String token = userEntity.getToken();
				 if (!StringUtils.isEmpty(token)){
					 redisTemplate.delete(token);
				 }
			 }
			 setMenuRedis( userId); //更新redis中的menu

		 }

		return R.ok();
	}
	
	@PostMapping("/updateRoleMenuInterface")
    @ApiOperation(value="更新/新增角色菜单-中间表接口")
	@SysAuthorityLog(value = "更新/新增角色菜单-中间表接口")
	@PreAuthorize("hasAuthority('sys:admin:update')")
	public R updateRoleMenu(@RequestBody RoleMenuVo roleMenuVo) {

			//roleMenuDao.delete(new QueryWrapper<RoleMenuEntity>().eq("role_id",roleMenuVo.getRoleId()));
		 roleMenuDao.deleteRoleMenuAndAuthority(roleMenuVo.getRoleId(),1);
			if(roleMenuVo.getMenuIds().length==0)  return R.ok();
				for(String menuId:roleMenuVo.getMenuIds()) {
					RoleMenuEntity roleMenuEntity = new RoleMenuEntity();
					roleMenuEntity.setRoleId(roleMenuVo.getRoleId());
					roleMenuEntity.setMenuId(Long.valueOf(menuId));
					roleMenuEntity.setIsDelete(0);
					//保存
					roleMenuService.saveE(roleMenuEntity);
				}

//			删除缓存中的登录状态，使权限重新生效
			Long roleId = roleMenuVo.getRoleId();
			List<UserRoleEntity> userRoleEntities = userRoleDao.selectList(new QueryWrapper<UserRoleEntity>().eq("role_id", roleId));
			if (!CollectionUtils.isEmpty(userRoleEntities)){
				for (UserRoleEntity userRoleEntity : userRoleEntities) {
					Long userId = userRoleEntity.getUserId();
					UserEntity userEntity = userService.getByIdE(userId);
					if (!ObjectUtils.isEmpty(userEntity)){
						String token = userEntity.getToken();
						if (!StringUtils.isEmpty(token)){
							redisTemplate.delete(token);
						}
					}

					setMenuRedis(userId); //更新该角色下的用户的菜单
				}
			}

		 return R.ok();
	}



	@PostMapping("/updateRoleAuthorityInterface")
	@ApiOperation(value="更新/新增角色功能-中间表接口")
	@SysAuthorityLog(value = "更新/新增角色功能-中间表接口")
	@PreAuthorize("hasAuthority('sys:admin:update')")
	public R updateRoleMenuAuthorityInterface(@RequestBody RoleMenuVo roleMenuVo) {

		//roleMenuDao.delete(new QueryWrapper<RoleMenuEntity>().eq("role_id",roleMenuVo.getRoleId()));
		roleMenuDao.deleteRoleMenuAndAuthority(roleMenuVo.getRoleId(),2);
		if(roleMenuVo.getMenuIds()==null||roleMenuVo.getMenuIds().length==0)  return R.ok();
		for(String menuId:roleMenuVo.getMenuIds()) {
			RoleMenuEntity roleMenuEntity = new RoleMenuEntity();
			roleMenuEntity.setRoleId(roleMenuVo.getRoleId());
			roleMenuEntity.setMenuId(Long.valueOf(menuId));
			roleMenuEntity.setIsDelete(0);
			//保存
			roleMenuService.saveE(roleMenuEntity);
		}

//			删除缓存中的登录状态，使权限重新生效
		Long roleId = roleMenuVo.getRoleId();
		List<UserRoleEntity> userRoleEntities = userRoleDao.selectList(new QueryWrapper<UserRoleEntity>().eq("role_id", roleId));
		if (!CollectionUtils.isEmpty(userRoleEntities)){
			for (UserRoleEntity userRoleEntity : userRoleEntities) {
				Long userId = userRoleEntity.getUserId();
				UserEntity userEntity = userService.getByIdE(userId);
				if (!ObjectUtils.isEmpty(userEntity)){
					String token = userEntity.getToken();
					if (!StringUtils.isEmpty(token)){
						redisTemplate.delete(token);
					}
				}

				setMenuRedis(userId); //更新该角色下的用户的菜单
			}
		}

		return R.ok();
	}

	
	@PostMapping("/updateRoleInterface")
	@ApiOperation(value = "角色更新接口")
	@SysAuthorityLog(value = "角色更新接口")
	@PreAuthorize("hasAuthority('sys:admin:update')")
	@Transactional
	public R updateRole(@RequestBody RoleEntity roleEntity) {
		//更新
		roleService.updateByIdE(roleEntity);
	//			删除缓存中的登录状态，使权限重新生效
		Long roleId = roleEntity.getRoleId();
		List<UserRoleEntity> userRoleEntities = userRoleDao.selectList(new QueryWrapper<UserRoleEntity>().eq("role_id", roleId));
		if (!CollectionUtils.isEmpty(userRoleEntities)){
			for (UserRoleEntity userRoleEntity : userRoleEntities) {
				Long userId = userRoleEntity.getUserId();
				UserEntity userEntity = userService.getByIdE(userId);
				if (!ObjectUtils.isEmpty(userEntity)){
					String token = userEntity.getToken();
					if (!StringUtils.isEmpty(token)){
						redisTemplate.delete(token);
					}
				}
				setMenuRedis( userId); //更新redis中的menu
			}
		}
		return R.ok();
	}
	
	@PostMapping("/updateMenuInterface")
	@ApiOperation(value = "菜单更新接口")
	@SysAuthorityLog(value = "菜单更新接口")
	@PreAuthorize("hasAuthority('sys:admin:update')")
	@Transactional
	public R update(@RequestBody MenuEntity menuEntity) {
		//更新
		return menuService.updateByIdE(menuEntity);
	}
	
	@PostMapping("/updateUserGroupInterface")
    @ApiOperation(value="用户组更新/新增接口")
	@SysAuthorityLog(value = "用户组更新/新增接口")
	@PreAuthorize("hasAuthority('sys:admin:update')")
    @Transactional
	public R updateUserGroup(@RequestBody @Valid UserGroupVo userGroupVo) {
		
		if(!ObjectUtils.isEmpty(userGroupVo)) {
			userGroupDao.deleteUserGroup(userGroupVo.getUserId());
			//userGroupService.removeOneById(userGroupVo.getUserId());
			for(String item : userGroupVo.getGroupIds()) {
				UserGroupEntity userGroup = new UserGroupEntity();
				userGroup.setUserId(userGroupVo.getUserId());
				userGroup.setGroupId(Long.parseLong(item));
				
				userGroupService.saveE(userGroup);
			}
			loginController.updateUsrOrgPermission(userGroupVo.getUserId());
		}
		
		return R.ok();
		
	}
	
	@PostMapping("/updateOrgGroupInterface")
    @ApiOperation(value="更新公司组接口")
	@SysAuthorityLog(value = "更新公司组接口")
    @Transactional
	@PreAuthorize("hasAuthority('group:admin:update')")
	public R updateOrgGroup(@RequestBody @Valid OrgGroupVo orgGroupVos) {
		Long groupId = orgGroupVos.getGroupId();
		if(!ObjectUtils.isEmpty(orgGroupVos)) {
			Timestamp d = new Timestamp(System.currentTimeMillis());
			if(ObjectUtils.isEmpty(orgGroupVos.getGroupId())){
			    Long id = snowflakeIdWorker.nextId();
			    orgGroupVos.setGroupId(id);
            }
			orgGroupDao.deleteOrgGroup(orgGroupVos.getGroupId());
			//orgGroupService.removeOneById(orgGroupVos.getGroupId());
			for(OrgGroupEntity item:orgGroupVos.getOrgGroupEntitys()) {
				OrgGroupEntity orgGroupEntity = new OrgGroupEntity();
				orgGroupEntity.setGroupId(orgGroupVos.getGroupId());
				orgGroupEntity.setOrgId(item.getOrgId());
				orgGroupEntity.setGroupName(item.getGroupName());
				orgGroupEntity.setOrgName(item.getOrgName());
				orgGroupEntity.setIsDelete(0);
				orgGroupEntity.setCreateTime(d);
				//新增保存
				orgGroupService.saveE(orgGroupEntity);
			}
		}

		List <UserGroupEntity> list = userGroupDao.selectList(new QueryWrapper<UserGroupEntity>().eq("group_id",groupId));
		//查找权限修改过的用户
		for(UserGroupEntity entity:list){
			Long userId = entity.getUserId();
			loginController.updateUsrOrgPermission(userId);
		}

		return R.ok();
	}

	@DeleteMapping("/deleteUserRoleInterface")
    @ApiOperation(value="删除用户角色-中间表接口")
	@SysAuthorityLog(value = "删除用户角色-中间表接口")
    @Transactional
	@PreAuthorize("hasAuthority('sys:admin:update')")
	public R deleteUserRole(Long userId) {
		//逻辑删除
		userRoleDao.updateUserRole(userId);

		UserEntity userEntity = userService.getByIdE(userId);
		String token = userEntity.getToken();
		redisTemplate.delete(token);
		setMenuRedis( userEntity.getUserId()); //刷新redis菜单权限

		return R.ok();
	}
	
	@DeleteMapping("/dateleRoleMenuInterface")
    @ApiOperation(value="删除角色菜单-中间表接口")
	@SysAuthorityLog(value = "删除角色菜单-中间表接口")
    @Transactional
	@PreAuthorize("hasAuthority('sys:admin:update')")
	public R deleteRoleMenu(Long roleId) {
		//逻辑删除
		roleMenuDao.updateRoleMenu(roleId);

		List<UserRoleEntity> userRoleEntities = userRoleDao.selectList(new QueryWrapper<UserRoleEntity>().eq("role_id", roleId));
		if (!CollectionUtils.isEmpty(userRoleEntities)){
			for (UserRoleEntity userRoleEntity : userRoleEntities) {
				Long userId = userRoleEntity.getUserId();
				UserEntity userEntity = userService.getByIdE(userId);
				if (!ObjectUtils.isEmpty(userEntity)){
					String token = userEntity.getToken();
					if (!StringUtils.isEmpty(token)){
						redisTemplate.delete(token);
					}
				}

				setMenuRedis(userId); //更新该角色下的用户的菜单
			}
		}
		return R.ok();
	}
	
	@DeleteMapping("/dateleRoleInterface")
	@ApiOperation(value = "角色删除接口")
	@SysAuthorityLog(value = "角色删除接口")
	@Transactional
	@PreAuthorize("hasAuthority('sys:admin:update')")
	public R deleteRole(Long roleId) {
		//逻辑删除
		R r = roleService.removeOneById(roleId);
		//			删除缓存中的登录状态，使权限重新生效

		List<UserRoleEntity> userRoleEntities = userRoleDao.selectList(new QueryWrapper<UserRoleEntity>().eq("role_id", roleId));
		if (!CollectionUtils.isEmpty(userRoleEntities)){
			for (UserRoleEntity userRoleEntity : userRoleEntities) {
				Long userId = userRoleEntity.getUserId();
				UserEntity userEntity = userService.getByIdE(userId);
				String token = userEntity.getToken();
				redisTemplate.delete(token);
				setMenuRedis( userId); //刷新redis菜单权限
			}
		}
		return r;
	}
	
	@DeleteMapping("/deleteMenuInterface")
	@ApiOperation(value = "菜单删除接口")
	@SysAuthorityLog(value = "菜单删除接口")
	@Transactional
	@PreAuthorize("hasAuthority('sys:admin:update')")
	public R deleteMenu(Long menuId) {
		//逻辑删除
		int i = menuDao.deleteById(menuId);
		if (i>0){
			return R.ok();
		}else {
			return R.error();
		}


	}
	
	@DeleteMapping("/deleteOrgGroupInterface")
    @ApiOperation(value="删除公司组接口")
	@SysAuthorityLog(value = "删除公司组接口")
    @Transactional
	@PreAuthorize("hasAuthority('group:admin:delete')")
	public R deleteOrgGroup(Long groupId) {
		//物理删除
		orgGroupDao.deleteOrgGroup(groupId);
		return R.ok();
	}

	@PostMapping("/updateUserRoleInterface")
	@ApiOperation(value="更新用户权限接口")
	@SysAuthorityLog(value = "更新用户权限接口")
	@PreAuthorize("hasAuthority('sys:admin:update')")
	public R updateUserRole(@RequestBody @Valid UserRoleVo userRoleVo) {

		//删除
		userRoleDao.delete(new QueryWrapper<UserRoleEntity>().eq("user_id",userRoleVo.getUserId()));
		//			删除缓存中的登录状态，使权限重新生效

		if (userRoleVo.getRoleIds()==null||userRoleVo.getRoleIds().size()==0) {
			Long userId = userRoleVo.getUserId();
			UserEntity userEntity = userService.getByIdE(userId);
			String token = userEntity.getToken();
			if(!StringUtils.isEmpty(token))
				redisTemplate.delete(token);
			setMenuRedis( userId); //刷新redis菜单权限
			return R.ok();
		}
		for (Long roleId:userRoleVo.getRoleIds()){
			UserRoleEntity userRoleEntity=new UserRoleEntity();
			userRoleEntity.setUserId(userRoleVo.getUserId());
			userRoleEntity.setRoleId(roleId);
			userRoleEntity.setIsDelete(0);
			int insert = userRoleDao.insert(userRoleEntity);
			if (insert<0){
				return R.error();
			}
		}

		Long userId = userRoleVo.getUserId();
		UserEntity userEntity = userService.getByIdE(userId);
		String token = userEntity.getToken();
		if(!StringUtils.isEmpty(token))
			redisTemplate.delete(token);
		setMenuRedis( userId); //刷新redis菜单权限
		//新增

		return R.ok();
	}
	@PostMapping("/getOrgGroupInterface")
	@ApiOperation(value="根据id获取公司组信息接口")
	@PreAuthorize("hasAuthority('group:admin:get')")
	public R getOrgGroup(@RequestBody String groupId) {
		return R.ok(orgGroupDao.getOrgGroupInfo(Long.valueOf(groupId)));
	}

	@GetMapping("/getUserOrgById")
	@ApiOperation(value="根据id查询公司组里的公司")
	@Transactional
	public R getUserOrgById(@RequestParam("userId") String userId) {
		return R.ok(userGroupDao.getUserOrgById(Long.valueOf(userId)));
	}


	private void setMenuRedis(Long userId) {
		List<String> menuByUserId = userDao.findMenuByUserId(userId);
		HashSet<String> hashSet = new HashSet<>();
		if (!CollectionUtils.isEmpty(menuByUserId)){
			for (String s : menuByUserId) {
				if (!StringUtils.isEmpty(s)){
					hashSet.add(s);
				}
			}
		}
		redisTemplate.boundValueOps("userMenu"+userId).set(hashSet);


	}
	
}

